﻿using Microsoft.EntityFrameworkCore;
using SheepStorage.Domain;
using SheepStorage.Domain.DTO.InputDto;
using SheepStorage.Domain.DTO.Output;
using SheepStorage.Domain.Entity;
using SheepStorage.Repository.Interface;
using SheepStorage.Service.Interface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Yitter.IdGenerator;

namespace SheepStorage.Service.DataImp
{
    public class SheepHybridizationService : ISheepHybridizationService
    {

        IBaseRepository<SheepRecord> _srres;
        IBaseRepository<SheepMomHybridization> _shres;
        IBaseRepository<BuildingManagement> _bmres;
        IBaseRepository<SheepField> _sfres;
        IBaseRepository<UserInfo> _ures;
        IBaseRepository<EarTagTable> _earres;
        IBaseRepository<SheepMomHistory> _mhres;


        public SheepHybridizationService(IBaseRepository<SheepRecord> srres, IBaseRepository<SheepMomHybridization> shres,
        IBaseRepository<BuildingManagement> bmres,
        IBaseRepository<SheepField> sfres, IBaseRepository<UserInfo> ures,
        IBaseRepository<EarTagTable> earres, IBaseRepository<SheepMomHistory> mhres)
        {
            _srres = srres;
            _shres = shres;
            _bmres = bmres;
            _sfres = sfres;
            _ures = ures;
            _earres = earres;
            _mhres = mhres;
        }

        /// <summary>
        /// 判断三代不能配种(根据种公查可配种种母)
        /// </summary>
        /// <param name="momsheep">种公耳号</param>
        /// <returns>可以配种的种公耳号列表</returns>
        public async Task<List<SheepRecord>> pz(string momsheep)
        {
            //获取全部可用种母
            var list = _srres.GetAll().Where(x => x.SheepRecordType == 2 && x.IsDel == false && x.SheepRecordBreedState <= 6).ToList();
            //定义输出集合
            var result = new List<SheepRecord>();

            // 获取种公信息
            var momsheepmom = _srres.GetAll().FirstOrDefault(x => x.OverBit == momsheep);
            //判断种公信息不为空
            if (momsheepmom != null)
            {
                // 种公判断是不是二代
                if (momsheepmom.SheepRecordMomOverbit != null && momsheepmom.SheepRecordDadOverbit != null)
                {
                    // 获取种母的祖父母信息
                    //姥姥耳号
                    var momMomMom = momsheepmom.SheepRecordMomOverbit != null ?
                                    _srres.GetAll().FirstOrDefault(x => x.OverBit == momsheepmom.SheepRecordMomOverbit)!.SheepRecordMomOverbit :
                                    null;
                    //姥爷耳号
                    var momMomDad = momsheepmom.SheepRecordMomOverbit != null ?
                                    _srres.GetAll().FirstOrDefault(x => x.OverBit == momsheepmom.SheepRecordMomOverbit)!.SheepRecordDadOverbit :
                                    null;
                    //奶耳号
                    var momDadMom = momsheepmom.SheepRecordDadOverbit != null ?
                                    _srres.GetAll().FirstOrDefault(x => x.OverBit == momsheepmom.SheepRecordDadOverbit)!.SheepRecordMomOverbit :
                                    null;
                    //爷耳号
                    var momDadDad = momsheepmom.SheepRecordDadOverbit != null ?
                                    _srres.GetAll().FirstOrDefault(x => x.OverBit == momsheepmom.SheepRecordDadOverbit)!.SheepRecordDadOverbit :
                                    null;
                    //种公判断是不是第三代
                    if (momMomMom != null && momMomDad != null && momDadMom != null && momDadDad != null)
                    {
                        //循环取到的种母(种公三代)
                        foreach (var item in list)
                        {

                            //判断种母是不是二代(种公三代)
                            if (item.SheepRecordMomOverbit != null && item.SheepRecordDadOverbit != null)
                            {

                                // 获取种母的祖父母信息
                                //姥姥耳号
                                var dadMomMom = (item.SheepRecordMomOverbit != null ?
                                                _srres.GetAll().FirstOrDefault(x => x.OverBit == item.SheepRecordMomOverbit)!.SheepRecordMomOverbit :
                                                null);
                                //姥爷耳号
                                var dadMomDad = item.SheepRecordMomOverbit != null ?
                                                _srres.GetAll().FirstOrDefault(x => x.OverBit == item.SheepRecordMomOverbit)!.SheepRecordDadOverbit :
                                                null;
                                //奶耳号
                                var dadDadMom = item.SheepRecordDadOverbit != null ?
                                                _srres.GetAll().FirstOrDefault(x => x.OverBit == item.SheepRecordDadOverbit)!.SheepRecordMomOverbit :
                                                null;
                                //爷耳号
                                var dadDadDad = item.SheepRecordDadOverbit != null ?
                                                _srres.GetAll().FirstOrDefault(x => x.OverBit == item.SheepRecordDadOverbit)!.SheepRecordDadOverbit :
                                                null;
                                //判断是不是三代(全是三代)
                                if (dadMomMom != null && dadMomDad != null && dadDadMom != null && dadDadDad != null)
                                {
                                    if (item.SheepRecordDadOverbit != momsheepmom.SheepRecordDadOverbit && item.SheepRecordDadOverbit != momDadDad && item.SheepRecordDadOverbit != momMomDad//种公他父不等种母三代
                                    && item.SheepRecordMomOverbit != momsheepmom.SheepRecordMomOverbit && item.SheepRecordMomOverbit != momMomMom && item.SheepRecordMomOverbit != momDadMom//种公他母不等于种母三代
                                    && momsheepmom.SheepRecordMomOverbit != dadDadMom && momsheepmom.SheepRecordMomOverbit != dadMomMom//种母他母不等种公他姥和奶
                                    && momsheepmom.SheepRecordDadOverbit != dadDadDad && momsheepmom.SheepRecordDadOverbit != dadMomDad//种母他父不等种公他爷
                                    && momDadDad != dadDadDad && momDadMom != dadDadMom && momMomDad != dadMomDad && momMomMom != dadMomMom
                                    && item.OverBit != momsheepmom.SheepRecordMomOverbit && momsheepmom.OverBit != item.SheepRecordDadOverbit
                                    && item.OverBit != momDadMom && item.OverBit != momMomMom && momsheepmom.OverBit != dadMomDad && momsheepmom.OverBit != dadDadDad
                                    && momDadMom != dadMomMom && momDadDad != dadMomDad && momMomDad != dadDadDad && momMomMom != dadDadMom)
                                    {
                                        result.AddRange(list.Where(x => x.OverBit == item.OverBit));
                                    }
                                }
                                else
                                {
                                    //判断是不是跟种公三代有关系(种公三代，种母二代)
                                    if (item.SheepRecordDadOverbit != momsheepmom.SheepRecordDadOverbit && item.SheepRecordDadOverbit != momDadDad && item.SheepRecordDadOverbit != momMomDad//种公他父不等种母三代
                                        && item.SheepRecordMomOverbit != momsheepmom.SheepRecordMomOverbit && item.SheepRecordMomOverbit != momMomMom && item.SheepRecordMomOverbit != momDadMom//种公他母不等于种母三代
                                        && momsheepmom.OverBit != item.SheepRecordDadOverbit//种公不等于种公他父
                                        && item.OverBit != momsheepmom.SheepRecordMomOverbit && item.OverBit != momDadMom && item.OverBit != momMomMom)//种母不等于他三代
                                    {
                                        result.AddRange(list.Where(x => x.OverBit == item.OverBit));
                                    }
                                }
                            }
                            else
                            {
                                //判断种母不是种母的父姥，奶
                                if (item.OverBit != momsheepmom.SheepRecordMomOverbit && item.OverBit != momDadMom && item.OverBit != momMomMom)
                                {
                                    result.AddRange(list.Where(x => x.OverBit == item.OverBit));
                                }
                            }
                        }
                    }
                    //循环取到的种母(种公二代)
                    foreach (var item in list)
                    {
                        //判断种母是不是二代
                        if (item.SheepRecordMomOverbit != null && item.SheepRecordDadOverbit != null)
                        {
                            // 获取种母的祖父母信息
                            //姥姥耳号
                            var dadMomMom = item.SheepRecordMomOverbit != null ?
                                            _srres.GetAll().FirstOrDefault(x => x.OverBit == item.SheepRecordMomOverbit)!.SheepRecordMomOverbit :
                                            null;
                            //姥爷耳号
                            var dadMomDad = item.SheepRecordMomOverbit != null ?
                                            _srres.GetAll().FirstOrDefault(x => x.OverBit == item.SheepRecordMomOverbit)!.SheepRecordDadOverbit :
                                            null;
                            //奶耳号
                            var dadDadMom = item.SheepRecordDadOverbit != null ?
                                            _srres.GetAll().FirstOrDefault(x => x.OverBit == item.SheepRecordDadOverbit)!.SheepRecordMomOverbit :
                                            null;
                            //爷耳号
                            var dadDadDad = item.SheepRecordDadOverbit != null ?
                                            _srres.GetAll().FirstOrDefault(x => x.OverBit == item.SheepRecordDadOverbit)!.SheepRecordDadOverbit :
                                            null;
                            //判断种母是不是三代
                            if (dadMomMom != null && dadMomDad != null && dadDadMom != null && dadDadDad != null)
                            {
                                //种公二代种母三代
                                if (item.OverBit != momsheepmom.SheepRecordMomOverbit
                                    && item.SheepRecordDadOverbit != momsheepmom.SheepRecordDadOverbit && momsheepmom.SheepRecordDadOverbit != dadDadDad && momsheepmom.SheepRecordDadOverbit != dadMomDad
                                    && momsheepmom.SheepRecordMomOverbit != item.SheepRecordMomOverbit && momsheepmom.SheepRecordMomOverbit != dadMomMom && momsheepmom.SheepRecordMomOverbit != dadDadMom
                                    && momsheepmom.OverBit != item.SheepRecordDadOverbit && momsheepmom.OverBit != dadMomDad && momsheepmom.OverBit != dadDadDad)
                                {
                                    result.AddRange(list.Where(x => x.OverBit == item.OverBit));
                                }
                            }
                            //种母二代，种公二代
                            else
                            {
                                if (item.OverBit != momsheepmom.SheepRecordMomOverbit && item.SheepRecordDadOverbit != momsheepmom.SheepRecordDadOverbit
                                && item.SheepRecordMomOverbit != momsheepmom.SheepRecordMomOverbit && momsheepmom.OverBit != item.SheepRecordDadOverbit)
                                {
                                    result.AddRange(list.Where(x => x.OverBit == item.OverBit));

                                }
                            }
                        }
                        else
                        {
                            //二代种公的父不等于种母（二代种母一代种公）
                            if (item.OverBit != momsheepmom.SheepRecordMomOverbit)
                            {
                                //不是二代直接填到集合里面
                                result.AddRange(list.Where(x => x.OverBit == item.OverBit));
                            }
                        }
                    }


                }
                else
                {
                    //循环所有种种母
                    foreach (var item in list)
                    {
                        //判断种母是不是二代
                        if (item.SheepRecordMomOverbit != null && item.SheepRecordDadOverbit != null)
                        {
                            // 获取种母的祖父母信息
                            //姥姥耳号
                            var dadMomMom = (item.SheepRecordMomOverbit != null ?
                                            _srres.GetAll().FirstOrDefault(x => x.OverBit == item.SheepRecordMomOverbit)!.SheepRecordMomOverbit :
                                            null);
                            //姥爷耳号
                            var dadMomDad = (item.SheepRecordMomOverbit != null ?
                                            _srres.GetAll().FirstOrDefault(x => x.OverBit == item.SheepRecordMomOverbit)!.SheepRecordDadOverbit :
                                            null);
                            //奶耳号
                            var dadDadMom = (item.SheepRecordDadOverbit != null ?
                                            _srres.GetAll().FirstOrDefault(x => x.OverBit == item.SheepRecordDadOverbit)!.SheepRecordMomOverbit :
                                            null);
                            //爷耳号
                            var dadDadDad = (item.SheepRecordDadOverbit != null ?
                                            _srres.GetAll().FirstOrDefault(x => x.OverBit == item.SheepRecordDadOverbit)!.SheepRecordDadOverbit :
                                            null);
                            //判断种母是不是三代
                            if (dadMomMom != null && dadMomDad != null && dadDadMom != null && dadDadDad != null)
                            {
                                //种公一代种母三代种公
                                if (item.SheepRecordDadOverbit != momsheepmom.OverBit
                                    && momsheepmom.OverBit != dadMomDad && momsheepmom.OverBit != dadDadDad)
                                {
                                    result.AddRange(list.Where(x => x.OverBit == item.OverBit));
                                }
                            }
                            //种公一代，种母二代
                            else
                            {
                                if (item.SheepRecordDadOverbit != momsheepmom.OverBit)
                                {
                                    result.AddRange(list.Where(x => x.OverBit == item.OverBit));

                                }
                            }
                        }
                        else
                        {
                            //不是二代直接填到集合里面
                            result.AddRange(list.Where(x => x.OverBit == item.OverBit));
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 种母配种显示
        /// </summary>
        /// <returns></returns>
        public async Task<List<SheepMomHybridizationOutput>> ShowHybridization(ShowHybridizationInput input)
        {
            var list = (from sh in _shres.GetAll().Where(x => x.IsDel != 1)
                        select new SheepMomHybridizationOutput
                        {
                            MomHybridizationId = sh.MomHybridizationId,
                            OverBit = sh.OverBit,
                            ElEarTag = sh.ElEarTag,
                            MomHybridizationVariety = sh.MomHybridizationVariety,
                            MomHybridizationDad = sh.MomHybridizationDad,
                            MomHybridizationDadVariety = sh.MomHybridizationDadVariety,
                            MomHybridizationType = sh.MomHybridizationType,
                            MomHybridizationHeatType = sh.MomHybridizationHeatType,
                            MomHybridizationScore = sh.MomHybridizationScore,
                            BuildingName = _bmres.GetAll().FirstOrDefault(x => x.BuildingManagementId == sh.BuildingName)!.BuildingName,
                            SheepFieldName = _sfres.GetAll().FirstOrDefault(x => x.SheepFieldId == sh.SheepFieldName)!.SheepFieldName,
                            NewBuildingName = _bmres.GetAll().FirstOrDefault(x => x.BuildingManagementId == sh.NewBuildingName)!.BuildingName,
                            NewSheepFieldName = _sfres.GetAll().FirstOrDefault(x => x.SheepFieldId == sh.NewSheepFieldName)!.SheepFieldName,
                            MomHybridizationState = sh.MomHybridizationState,
                            MomHybridizationDate = sh.MomHybridizationDate,
                            MomHybridizationLastDate = sh.MomHybridizationLastDate,
                            MomHybridizationWeight = sh.MomHybridizationWeight,
                            MomHybridizationRemark = sh.MomHybridizationRemark,
                            DocumentNumber = sh.DocumentNumber,
                            SerialNumber = sh.SerialNumber,
                            Uid = sh.Uid,
                            UName = _ures.GetAll().FirstOrDefault(x => x.UserId == sh.Uid)!.UserTrueName,
                            AddName = sh.AddName,
                            AddTime = sh.AddTime,
                            CheckDate = sh.CheckDate,
                            CheckUid = sh.CheckUid,
                            DelName = sh.DelName,
                            DelTime = sh.DelTime,
                            IsDel = sh.IsDel,
                            UpdateName = sh.UpdateName,
                            UpdateTime = sh.UpdateTime,
                            CheckUname = _ures.GetAll().FirstOrDefault(x => x.UserId == sh.CheckUid)!.UserTrueName
                        }).ToList();
            if (!string.IsNullOrEmpty(input.staDate))
            {
                list = list.Where(x => x.MomHybridizationDate >= DateTime.Parse(input.staDate)).ToList();
            }
            if (!string.IsNullOrEmpty(input.endDate))
            {
                list = list.Where(x => x.MomHybridizationDate <= DateTime.Parse(input.endDate)).ToList();
            }
            if (!string.IsNullOrEmpty(input.OverBit))
            {
                list = list.Where(x => x.OverBit.Contains(input.OverBit)).ToList();
            }
            if (input.Uid > 0)
            {
                list = list.Where(x => x.Uid == input.Uid).ToList();
            }
            list = list.OrderByDescending(x => x.MomHybridizationId).ToList();
            return list;
        }



        /// <summary>
        /// 批量审批
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="uname"></param>
        /// <returns></returns>
        public async Task<int> UpdCheck(string ids, string uname)
        {
            var id = ids.Split(',');
            int[] idss = id.Select(int.Parse).ToArray();
            var list = _shres.GetAll().Where(x => idss.Contains(x.MomHybridizationId)).ToList();
            foreach (var item in list)
            {
                item.UpdateName = uname;
                item.UpdateTime = DateTime.Now;
                item.CheckUid = _ures.GetAll().FirstOrDefault(x => x.UserTrueName == uname).UserId;
                item.CheckDate = DateTime.Now;
                item.MomHybridizationState = 9;
            }
            return _shres.UpdateRange(list);
        }

        /// <summary>
        /// 添加种母配种信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<int> AddSheepHybridization(List<AddSheepMomHybridizationInput> inputlist)
        {
            try
            {
                //事务
                using (TransactionScope scope = new TransactionScope()) 
                {
                    foreach(var input in inputlist)
                    {

                        var lis = new SheepMomHybridization
                        {
                            MomHybridizationId = 0,
                            OverBit = input.OverBit,
                            ElEarTag = input.OverBit,
                            MomHybridizationVariety = _srres.GetAll().FirstOrDefault(x => x.OverBit == input.OverBit).SheepRecordVariety,
                            MomHybridizationDad = input.MomHybridizationDad,
                            MomHybridizationDadVariety = _srres.GetAll().FirstOrDefault(x => x.OverBit == input.MomHybridizationDad).SheepRecordVariety,
                            MomHybridizationType = input.MomHybridizationType,
                            MomHybridizationHeatType = input.MomHybridizationHeatType,
                            MomHybridizationScore = input.MomHybridizationScore,
                            BuildingName = _bmres.GetAll().FirstOrDefault(x => x.BuildingName == input.BuildingName).BuildingManagementId,
                            SheepFieldName = _sfres.GetAll().FirstOrDefault(x => x.SheepFieldName == input.SheepFieldName).SheepFieldId,
                            NewBuildingName = input.NewBuildingName,
                            NewSheepFieldName = input.NewSheepFieldName,
                            MomHybridizationState = input.MomHybridizationState,
                            MomHybridizationDate = input.MomHybridizationDate,
                            MomHybridizationLastDate = input.MomHybridizationLastDate,
                            MomHybridizationWeight = input.MomHybridizationWeight,
                            MomHybridizationRemark = input.MomHybridizationRemark,
                            DocumentNumber = YitIdHelper.NextId().ToString(),
                            SerialNumber = YitIdHelper.NextId().ToString(),
                            AddName = input.AddName,
                            UpdateName = "",
                            DelName = "",
                            AddTime = DateTime.Now,
                            UpdateTime = null,
                            DelTime = null,
                            IsDel = 0,
                            Uid = input.Uid,
                            CheckUid = 0,
                            CheckDate = null
                        };
                        var list = _shres.Add(lis);
                        if (list > 0)
                        {
                            //修改羊只档案
                            var upd = _srres.GetAll().FirstOrDefault(x => x.OverBit == input.OverBit);
                            upd.BuildingName = _bmres.GetAll().FirstOrDefault(x => x.BuildingManagementId == input.NewBuildingName).BuildingName;
                            upd.SheepFieldName = _sfres.GetAll().FirstOrDefault(x => x.SheepFieldId == input.NewSheepFieldName).SheepFieldName;
                            upd.SheepRecordBreedState = input.MomHybridizationState;
                            upd.UpdateName = input.AddName;
                            upd.UpdateTime = DateTime.Now;
                            upd.SheepRecordGestation = 0;
                            _srres.Update(upd);


                            //添加种母历史
                            var sheep = new SheepMomHistory
                            {
                                MomHistoryId = 0,
                                OverBit = input.OverBit,
                                ElEarTag = input.OverBit,
                                MomHistoryDate = input.MomHybridizationDate,
                                MomHistoryDadOverbit = input.MomHybridizationDad,
                                MomHistoryPregnantDate = null,
                                MomHistoryPregnantResult = 0,
                                MomHistoryDeliveryDate = null,
                                MomHistoryHealth = 0,
                                MomHistoryHealthWeight = 0,
                                MomDeliveryWeak = 0,
                                MomDeliveryMalformation = 0,
                                MomDeliveryStillbirth = 0,
                                MomDeliveryMonster = 0,
                                MomDeliveryMummy = 0,
                                MomHistoryWeaningDate = null,
                                MomHistoryWeaningCount = 0,
                                MomHistoryWeaningWeight = 0,
                                MomHistoryParity = 0,
                                MomHistoryState = 0,
                                DocumentNumbe = YitIdHelper.NextId().ToString(),
                                SerialNumber = YitIdHelper.NextId().ToString(),
                                AddName = input.AddName,
                                UpdateName = null,
                                DelName = null,
                                AddTime = DateTime.Now,
                                UpdateTime = null,
                                DelTime = null,
                                IsDel = 0
                            };
                            _mhres.Add(sheep);

                        }
                    }
                    scope.Complete();  // 完成事务
                    return 1;//添加成功
                }
            }
            catch (Exception)
            {
                // 如果没有成功执行，则抛出异常，事务将自动回滚
                throw new Exception("操作失败");
            }
            
        }

        /// <summary>
        /// 批量删除种母配种（逻辑删）
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> DelSheepHybridzation(string? ids)
        {
            var id =  ids.Split(',');
            int[] ints= id.Select(x=>int.Parse(x.Trim())).ToArray();
            var list=_shres.GetAll().Where(x=>ints.Contains(x.MomHybridizationId)).ToList();
            foreach(var item in list)
            {
                item.IsDel = 1;
                item.DelTime = DateTime.Now;
            }
            return _shres.UpdateRange(list);
        }





    }
}
